#include "RecentModel.h"
#include "Settings.h"

#include <QStandardItem>
#include <QFileInfo>
#include <QDebug>

RecentModel::RecentModel(QObject *parent)
    : QStandardItemModel(parent)
{
    QHash<int, QByteArray> roles;
    roles[FileNameRole] = "fileName";
    roles[FilePathRole] = "filePath";
    //roles[FileIconRole] = "fileIcon";
    //roles[FileSizeRole] = "fileSize";
    //roles[FileTypeRole] = "fileType";
    setRoleNames(roles);

    updateList();
    connect(Settings::instance(), SIGNAL(valueChanged(QString)), this, SLOT(slotValueChanged(QString)));
}

RecentModel::~RecentModel()
{
}

QVariant RecentModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    switch (role) {
        case FileNameRole: {
            QString path = QStandardItemModel::data(index, Qt::DisplayRole).toString();
            return QFileInfo(path).fileName();
        }
        case Qt::DisplayRole:
        case FilePathRole:
            return QStandardItemModel::data(index, Qt::DisplayRole);
        default:
            break;
    }
    return QVariant();
}

void RecentModel::updateList()
{
    beginResetModel();
    clear();
    Q_FOREACH(const QVariant &v, Settings::instance()->valueList("recentFiles")) {
        QString s = v.toString();
        if (s.isEmpty())
            continue;
        QStandardItem *item = new QStandardItem(s);
        appendRow(item);
    }
    endResetModel();
}

void RecentModel::slotValueChanged(const QString &name)
{
    if (name == QLatin1String("recentFiles"))
        updateList();
}
